<?php
/**
 * Created by PhpStorm.
 * User: xrr
 * Date: 18-9-5
 * Time: 下午6:45
 */

namespace App\Http\Controllers;


use App\Apply;
use App\Key;
use App\Mail\applySend;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Exception;
use Illuminate\View\View;
use Validator;

class TeacherController extends Controller
{
    public function __construct(Request $request)
    {
        if(!$request->has('sid')){

            $this->middleware('auth');
        }

    }

    public function index(Request $request){
        $nowMonth=date( "Y-m");
        $recent=Apply::where([
            'check_status' => Apply::APPLY_CHECKING,

        ])->where('apply_time','like',"%$nowMonth%")->orderBy('created_at','desc')->get();
        $keyUser= Key::find(1);
        return View('teacher.index',['recent'=>$recent,'key_user'=>$keyUser]);
    }

    public function history(Request $request){

        $nowYear=date( "Y");
        $applies=Apply::where('apply_time','like',"%$nowYear%")->orderBy('created_at','desc')->get();
        $all=[];
        foreach ($applies as $apply){
            $time=str_replace($nowYear.'-','',$apply->apply_time);
            $month=substr($time,0,2);

            for($i=1;$i<=12;$i++){

                if((string)$i==$month){
                    if(!isset($all[$i])){
                        $all[$i]=[];
                    }
                    array_push($all[$i],$apply);
                }
            }
        }
        return View('teacher.history',['all'=>$all]);
    }

    public function setKeyUser(Request $request){

        $key = Key::firstOrCreate(['id'=>1]);
        $va= Validator::make($request->all(),[
            'email'  => 'required|email',
            'name'   => 'required|string',
            'phone'  => 'required|digits:11',
        ],[
            'email.required' => '邮件地址必填',
            'email.email'    => '邮件地址格式不正确',
            'name.required'  => '管理员名字必填',
            'phone.required' => '电话必填',
            'phone.digits'   => '电话格式不正确',
        ]);
        if($va->fails()) {
            return api_response('validate_fail',[],$va->errors()->first());
        }

        if(!$key->fill($request->all())->save()){
            return api_response('fail',[],'钥匙管理员设置失败');
        }
        return api_response('ok',$key->toArray(),'钥匙管理员设置成功');
    }

    public function passApply(Request $request){

        if(!$request->has('id')){
            return api_response('fail',[],"请输入id");
        }

        $id=$request->id;

        $apply=Apply::find($id);

        $apply->check_status=Apply::APPLY_PASSED;

        $user=User::all()->first();

        if($apply->save()){

            $this->sendPassEmail($apply,$user);
            $this->sendPassToKeyUser($apply,$user);
        }
        if($request->has('sid')){
            return '<h1>审核通过！</h1>';
        }

        return api_response('ok',[],'申请通过成功');

    }

    public function denyApply(Request $request){

        if(!$request->has('id')){
            return api_response('fail',[],"请输入id");
        }

        $id=$request->id;

        $apply=Apply::find($id);

        $apply->check_status=Apply::APPLY_REFUSED;

        $user=User::all()->first();

        if($apply->save()){

            $this->sendFailEmail($apply,$user);
        }

        if($request->has('sid')){
            return '<h1>审核拒绝！</h1>';
        }

        return api_response('ok',[],'申请拒绝成功');

    }

    public function deleteApply(Request $request){

        if(!$request->has('id')){
            return api_response('fail',[],"请输入id");
        }

        $id=$request->id;

        $apply=Apply::find($id);

        if(!$apply->delete()){
            return api_response('fail',[],'删除失败');
        }
        return api_response('ok',[],'删除成功');
    }

    public function  sendPassEmail($apply,$user){

        $when = Carbon::now()->addMinutes(1);
        try {
            Mail::to($apply->email)
                ->later($when, new applySend($apply,$user, "email.sendPassApply",'','',Key::find(1)));

        }catch (Exception $e){
            Mail::to($apply->email)
                ->later($when, new applySend($apply,$user, "email.sendPassApply",'',''),Key::find(1));
        }
    }

    public function  sendFailEmail($apply,$user){
        $when = Carbon::now()->addMinutes(1);

        try {
            Mail::to($apply->email)
                ->later($when, new applySend($apply,$user, "email.sendFailApply",'',''));

        }catch (Exception $e){
            Mail::to($apply->email)
                ->later($when, new applySend($apply,$user, "email.sendFailApply",'',''));
        }
    }

    public function  sendPassToKeyUser($apply,$user){
        $keyUser = Key::all()->first();

        if(empty($keyUser)){
            return;
        }

        $when = Carbon::now()->addMinutes(1);
        try {
            Mail::to($keyUser->email)
                ->later($when, new applySend($apply,$user,'email.sendPassKeyUser','','',$keyUser));

        }catch (Exception $e){
            Mail::to($keyUser->email)
                ->later($when, new applySend($apply,$user,'email.sendPassKeyUser','','',$keyUser));
        }

    }


}